/**
 * Created by ahwwl on 17-9-7.
 */

(function (original) {
    jQuery.fn.clone = function () {
        var result = original.apply(this, arguments),
            my_textareas = this.find('textarea').add(this.filter('textarea')),
            result_textareas = result.find('textarea').add(result.filter('textarea')),
            my_selects = this.find('select').add(this.filter('select')),
            result_selects = result.find('select').add(result.filter('select'));

        for (var i = 0, l = my_textareas.length; i < l; ++i) $(result_textareas[i]).val($(my_textareas[i]).val());
        for (var i = 0, l = my_selects.length; i < l; ++i) result_selects[i].selectedIndex = my_selects[i].selectedIndex;

        return result;
    };
}) (jQuery.fn.clone);
 var fDialog =
    {
        zIndex:10000,
        open:function(s)
        {
            var times = (new Date()).valueOf();
            var default_s = {
                type: 1,
                title: '提示',
                closeBtn: true,
                shade: 0.65,
                area: ['100%', "100%"],
                content: '',
                clone:false,
                btn: ['确定','取消'],
                id:"f_dialog_"+times,
                zIndex: fDialog.zIndex,
                yes: null,
                cancel: null,
                success: null,
                end:null,
                skin:null,
                scrollbar:false,
                time:0
            };
            s = $.extend({},default_s,s);
            fDialog.create(s);

        },
        msg:function (s) {
            var times = (new Date()).valueOf();
            var default_s = {
                type: 0,
                title: '',
                closeBtn: false,
                shade: 0,
                area: ['100%', "100%"],
                content: '',
                clone:false,
                btn: ['确定','取消'],
                id:"f_dialog_"+times,
                zIndex: fDialog.zIndex,
                yes: null,
                cancel: null,
                success: null,
                end:null,
                skin:"f-dialog-msg",
                scrollbar:true,
                time:2000
            };
            s = $.extend({},default_s,s);
            fDialog.create(s);
        },
        prompt:function (content,yes,cancel) {
            if(!content)
            {
                content = '<input type="text" name="" value="" class="f-dialog-input">';
            }
            var times = (new Date()).valueOf();
            var default_s = {
                type: 0,
                title: '信息',
                closeBtn: true,
                shade: 0.65,
                area: ['300px', "160px"],
                content: content,
                clone:false,
                btn: ['确定','取消'],
                id:"f_dialog_"+times,
                zIndex: fDialog.zIndex,
                yes: function (index,obj,e) {
                    var value = obj.find(".f-dialog-input").val();
                    if(yes)
                    {
                        var r = yes(value);
                        if(r === false)
                        {
                            e.stopPropagation();
                            return false;
                        }
                    }
                    fDialog.close(obj);
                },
                cancel: cancel,
                success: null,
                end:null,
                scrollbar:false,
                skin:"",
                time:0
            };
            fDialog.create(default_s);
        },
        create:function (s) {

            var settimeoutobj = null;
            var dialog = $("<div class='f-dialog'></div>");
            var backdrop = $('<div class="f-modal-backdrop f-fade in"></div>');
            var modal = $('<div class="f-modal"></div>');
            var modal_dialog = $('<div class="f-modal-dialog" tabindex="-1" ></div>');
            var modal_content = $('<div class="f-modal-content"></div>');
            var modal_header = $('<div class="f-modal-header"></div>');
            var modal_body = $('<div class="f-modal-body"></div>');
            var modal_footer = $('<div class="f-modal-footer"></div>');
            fDialog.zIndex += 1;
            backdrop.css("z-index",fDialog.zIndex);
            fDialog.zIndex += 1;
            modal.css("z-index",fDialog.zIndex);
            if(s.closeBtn)
            {
                modal_header.append('<button class="f-close" type="button">×</button>');
            }
            modal_header.append('<h4 class="f-modal-title">'+s.title+'</h4>');
            if(s.clone && $.type(s.content) == "object")
            {
                s.content = s.content.clone(true,true);
            }
            if(s.type == 0 )
            {
                modal_body.append(s.content);
            }
            else if(s.type == 1)
            {
                if($.type(s.content) == "object")
                {
                    s.content.show();
                }
                modal_body.append(s.content);
            }else if(s.type == 2)
            {
                if(s.content)
                {
                    var modal_iframe = $('<iframe src=""  scrolling="auto" frameborder="0"></iframe>');
                    modal_iframe.attr("src",s.content);
                    modal_body.append(modal_iframe);
                }
            }
            if(s.btn.length>0)
            {
                for(var i=0;i<s.btn.length;i++)
                {
                    modal_footer.append('<a class="f-btn">'+s.btn[i]+'</a>');
                }
                modal_footer.find(".f-btn").each(function (ii) {
                    if(ii == 0)
                    {
                        $(this).addClass("f-btn-success");
                        if(s.yes)
                        {
                            fDialog.clickBind($(this),s.yes)
                        }
                    }else if(ii == 1)
                    {
                        $(this).addClass("f-btn-danger").addClass("f-close");
                        if(s.cancel)
                        {
                            fDialog.clickBind($(this),s.cancel)
                        }
                    }else{
                        $(this).addClass("f-btn-primary");
                    }
                    if(s["btn"+(ii+1)])
                    {
                        fDialog.clickBind($(this),s["btn"+(ii+1)])
                    }
                });
            }
            dialog.attr({id:s.id});
            modal_header.appendTo(modal_content);
            modal_body.appendTo(modal_content);
            modal_footer.appendTo(modal_content);
            modal_content.appendTo(modal_dialog);
            modal_dialog.appendTo(modal);
            modal.appendTo(dialog);
            backdrop.appendTo(dialog);
            dialog.appendTo($("body"));
            if(s.skin)
            {
                dialog.addClass(s.skin);
            }

            if(s.area)
            {
                var w = "100%";
                var h = "100%";
                if($.isArray(s.area))
                {
                    w = s.area[0];
                    if(s.area.length>1)
                    {
                        h = s.area[1];
                    }
                }else if($.type(s.area) == "string")
                {
                    w = s.area;
                }
                w = w.replace(";","");
                h = h.replace(";","");
                modal_dialog.css({"width":w,"height":h});




            }
            if(s.shade && $.isNumeric(s.shade))
            {
                backdrop.css("opacity",s.shade);
            }

            $("body>div.f-dialog").each(function (i) {
                if($(this).attr("id") === s.id)
                {
                    s.index = i;
                }

            });

            dialog.find(".f-close").click(function (e) {
                if(!e.isPropagationStopped())
                {
                    fDialog.close(dialog);
                }

            });
            dialog[0].close = function () {
                fDialog.close(dialog);
            };
            dialog[0].config = s;
            if(s.success)
            {
                s.success(dialog);
            }
            if(s.end)
            {
                s.end(dialog);
            }
            if(s.time)
            {

                settimeoutobj = setTimeout(function () {
                    fDialog.close(dialog);
                },s.time);
            }
            modal_dialog.click(function () {
                if(modal_dialog.find("input:focus,select:focus,textarea:focus").length<1)
                {
                    $(this).focus();
                }
            });
            modal.click(function () {
               if(!$(this).find(".f-modal-dialog,.f-modal-dialog input:focus,.f-modal-dialog select:focus,.f-modal-dialog textarea:focus").is(":focus"))
               {
                   if(settimeoutobj)
                   {
                       clearTimeout(settimeoutobj);
                   }

                   fDialog.close(dialog);
               }
            });
            fDialog.resize();
            if(!s.scrollbar)
            {
                $("body").addClass("f-modal-open");
            }
            // modal_dialog.show();


        },
        resize:function()
        {
            $(".f-modal-dialog").each(function () {
                var w1 = $(window).width();
                var w2 = $(this).attr("data-width");
                var h1 = $(window).height();
                var h2 = $(this).attr("data-height");
                if(!w2)
                {
                    w2 = $(this).width();
                    $(this).attr("data-width",w2);
                }
                if(!h2)
                {
                    h2 = $(this).height();
                    $(this).attr("data-height",h2);
                }


                if(w2>(w1-50))
                {
                    $(this).css("width","100%");
                }else{
                    $(this).width(w2);
                }
                if(h2>h1)
                {
                    $(this).css("height","100%");
                }else{
                    $(this).height(h2);
                }
            })
        },
        close:function (index) {

            var obj = $("body>div.f-dialog").eq(index);
            if($.type(index) == "object")
            {
                obj = index;
            }
            if(obj.length>0)
            {
                obj.remove();
                if($("body>div.f-dialog").length<2)
                {
                    $("body").removeClass("f-modal-open");
                }
                // obj.fadeTo("slow", 0.01, function(){//fade
                //     $(this).slideUp(100, function() {//slide up
                //         $(this).remove();//then remove from the DOM
                //
                //     });
                // });
                // obj.remove();
            }
        },
        clickBind:function (obj,callback) {
            obj.click(function (e) {
                var config = obj.parents(".f-dialog")[0].config;
                var r = callback(config.index,obj.parents(".f-dialog"),e);
                if(r === false)
                {
                    e.stopPropagation();
                    return false;
                }
            });
        }
    };

 $(function () {
    $(window).resize(function () {
        fDialog.resize();
    });
 });
(function($){
    $.fn.close = function () {
        $(this).each(function () {
           if($(this)[0].close &&$(this).hasClass("f-dialog"))
           {
               $(this)[0].close();
           }
        });
    }
})(jQuery);
